package com.example.demo.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.custom.AjaxResult;
import com.example.demo.entity.CarKeep;
import com.example.demo.entity.CarKeep2;
import com.example.demo.form.CarKeepForm;
import com.example.demo.service.CarKeep2Service;
import com.example.demo.service.CarKeepService;

@RestController
@RequestMapping(value = "/CarKeep2")
public class CarKeep2Controller {
	@Autowired
	private CarKeepService service1;
	@Autowired
	private CarKeep2Service service2;
	
	private DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
	
	@RequestMapping(value = "/save")
	private Object save(CarKeepForm From) throws ParseException {
		Integer carid1=From.getId();
		Date d=new Date();
		Date d1=dateFormat1.parse("1999-09-09");
		CarKeep car=new CarKeep();
		CarKeep Car=new CarKeep();
		CarKeep2 car2=new CarKeep2();
		CarKeep2 Car2=new CarKeep2();
		if(carid1==null) {
			Car.setName(From.getName());
			car=service1.save(Car);
		}else {
			car=service1.findById(carid1);
			car.setName(From.getName());
			service1.save(car);
			List<CarKeep2> list=service2.findByCarKeep(car);
			for(CarKeep2 carKeep2:list) {
				if(d1.compareTo(carKeep2.getBeginDate())==-1) {
					d1=carKeep2.getBeginDate();
					Car2=carKeep2;
				}
			}
			Car2.setEndDate(d);
			service2.save(Car2);
		}
		BeanUtils.copyProperties(From, car2,"id","name");
		car2.setCarKeep(car);
		car2.setBeginDate(d);
		service2.save(car2);
		return new AjaxResult("数据保存成功");
		
	}
	
	@RequestMapping(value = "/list")
	private Object list() {
		return new AjaxResult(service1.findAll());
	}
	
	@RequestMapping(value = "/findbyId")
	private Object findbyId(Integer id) throws ParseException {
		List<CarKeep2> list=service2.findByCarKeepId(id);
		Date d=dateFormat1.parse("1999-01-01");
		CarKeep2 car=new CarKeep2();
		for(CarKeep2 y:list) {
			if(d.compareTo(y.getBeginDate())==-1) {
				d=y.getBeginDate();
				car=y;
			}
		}
		return new AjaxResult(car);
	}
}
